import router from "@/router"
import service from "@/utils/httpRequest"
import { Message } from "element-ui"


export default {
  namespaced: true,
  state: () => ({
    loginUser: { userName: "未登录",role: null},
    isShowingLoginPrompt: false, // 新增状态 
    cookies:""
  }),
  actions: {
    async getLoginUser({ commit, state }, payload) {
      try {
        const res = await service.get('/lovehelp/fellow/get/login') 
        console.log("  获取登录用户信息", res)
        if (res.code  === 200) {
          commit('updateUser', res.data)  
        } else if (res.code  === 40101) {
          commit('updateUser', {
            userName: "未登录", 
            role: null 
          })
          // 只有在当前路由不是登录页时才跳转 
          if (router.currentRoute.path  !== '/login' && !state.isShowingLoginPrompt) {
            commit('setShowingLoginPrompt', true)
            Message.error("请先登录")
            router.push('/login') 
            setTimeout(() => commit('setShowingLoginPrompt', false), 2000) // 2秒后重置状态 
          }
        }
      } catch (error) {
        console.error('  用户信息获取失败:', error)
      }
    }
  },
  mutations: {
    updateUser(state, payload) {
      state.loginUser  = payload 
      console.log("  更新用户信息", state.loginUser)
    },
    setShowingLoginPrompt(state, value) { // 新增mutation 
      state.isShowingLoginPrompt  = value 
    }
  }
}